package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQuery;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 13925 on 2018/11/1.
 */

@RestController
@RequestMapping("/region")
public class RegionsController {
    @Autowired
    private IRegionService regionService;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ServletContext servletContext;

    @GetMapping
    public List<Region> get() {
        List<Region> list = regionService.selectAll();
        return list;
    }

    @GetMapping("/{state}")
    public List<Region> listByState(@PathVariable Long state) {
        return regionService.listByState(state);
    }


    @GetMapping(value = "/{regionId}/strategies", produces = "application/html;charset-utf-8")
    public void getStrategiesByRegionIdHtml(StrategyQuery qo, HttpServletResponse response) throws Exception {
        //当前地区推荐攻略
        qo.setState(Strategy.STATE_HOT); //推荐状态
        qo.setPageSize(0);   //不需要分页
        PageInfo commends = strategyService.query(qo); //推荐

        //当前地区全部攻略
        qo.setState(-1);   //查全部
        qo.setPageSize(9); //要分页
        PageInfo alls = strategyService.query(qo); //全部


        //数据+ 模板
        //模板配置对象
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);

        //设置模板目录
        cfg.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("/template")));
        //获取模板对象
        Template template = cfg.getTemplate("strategyPage.ftl");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("commends", commends);
        map.put("alls", alls);
        //合并和输出
        //参数1:数据
        //参数2:合成之后输出到哪里去
        template.process(map, response.getWriter());
    }

    //表示输出数据是json格式
    @GetMapping(value = "/{regionId}/strategies", produces = "application/json;charset-utf-8")
    public PageInfo getStrategiesByRegionIdJson(StrategyQuery qo) {
        qo.setPageSize(9);
        return strategyService.query(qo);
    }
}
